package com.base.vistter.iframe.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.base.vistter.iframe.entity.SysRole;
import com.base.vistter.iframe.entity.SysRoleMenu;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.mapper.SysRoleMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class SysRoleMenuService extends BaseService<SysRoleMenuMapper, SysRoleMenu> {

    @Transactional(propagation = Propagation.REQUIRED)
    public Boolean permission(SysRole sysRole) throws IframeException{
        LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<SysRoleMenu>();
        lambdaQueryWrapper.eq(SysRoleMenu::getRoleId , sysRole.getId());
        super.delete(lambdaQueryWrapper);
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        if(sysRole.getMenuIds() != null && sysRole.getMenuIds().size() > 0){
            for(int i = 0 ; i < sysRole.getMenuIds().size(); i++){
                list.add(new SysRoleMenu(sysRole.getId(), sysRole.getMenuIds().get(i)));
            }
        }
        return super.saveBatch(list);
    }

    @Transactional(readOnly = true)
    public List<Integer> getMenuIds(Integer roleId) throws IframeException{
        LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<SysRoleMenu>();
        lambdaQueryWrapper.eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> list = super.selectList(lambdaQueryWrapper);
        return list.stream().map(e -> e.getMenuId()).collect(Collectors.toList());
    }
    @Transactional(readOnly = true)
    public List<SysRoleMenu> getRoleMenuList(Integer roleId) throws IframeException{
        LambdaQueryWrapper<SysRoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<SysRoleMenu>();
        lambdaQueryWrapper.eq(SysRoleMenu::getRoleId , roleId);
        return super.selectList(lambdaQueryWrapper);
    }
}
